<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="订阅ID" prop="usersubId">
        <el-input v-model="queryParams.usersubId" placeholder="请输入订阅ID" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="定时名称" prop="timerName">
        <el-select v-model="queryParams.timerName" placeholder="请选择定时器名" clearable filterable @change="handleQuery">
          <el-option v-for="item in timerNameOptions" :key="item" :label="item" :value="item" />
        </el-select>
      </el-form-item>
      <el-form-item label="订阅名称" prop="usersubId">
        <el-select v-model="queryParams.usersubId" placeholder="请选择订阅名称" clearable filterable @change="handleQuery">
          <el-option v-for="item in usersubOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>


      <!-- <el-form-item label="开始时间" prop="effectiveStartTime">
        <el-date-picker clearable v-model="queryParams.effectiveStartTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预警开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束时间" prop="effectiveEndTime">
        <el-date-picker clearable v-model="queryParams.effectiveEndTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择预警结束时间">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="检测间隔" prop="pollInterval">
        <el-input v-model="queryParams.pollInterval" placeholder="请输入检测间隔" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->


      <el-form-item label="状态" prop="timerStatus">
        <el-select v-model="queryParams.timerStatus" placeholder="请选择状态" filterable clearable @change="handleQuery">
          <el-option label="启动" value="active" />
          <el-option label="挂起" value="close" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <!-- <el-form-item label="创建时间" prop="createTime">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择创建时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间" prop="updateTime">
        <el-date-picker clearable v-model="queryParams.updateTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:timers:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:timers:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:timers:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['system:timers:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="timersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="timerId" />
      <el-table-column label="定时器名称" width="150" align="center" prop="timerName" />
      <el-table-column label="订阅名称" align="center" prop="usersubName" />
      <el-table-column label="预警周期" align="center" width="200">
        <template #default="scope">
          <span>
            {{ parseTime(scope.row.effectiveStartTime, '{y}-{m}-{d}') }} 至
            {{ parseTime(scope.row.effectiveEndTime, '{y}-{m}-{d}') }}
          </span>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="timerStatus" width="120">
        <template #default="scope">
          <el-tag :type="scope.row.timerStatus === 'active' ? 'success' : 'info'" effect="dark"
            style="cursor: default;">
            {{ scope.row.timerStatus === 'active' ? '启动' : '挂起' }}
          </el-tag>
        </template>
      </el-table-column>


      <el-table-column label="轮询类型" align="center" prop="pollType">
        <template #default="scope">
          <span>{{ scope.row.pollType === 'fixedtime' ? '固定时间' : '时间间隔' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="检测间隔" width="150" align="center" prop="pollInterval">
        <template #default="{ row }">
          {{ row.pollInterval !== null && row.pollInterval !== undefined && row.pollInterval !== ''
            ? row.pollInterval + '小时'
            : '未设置' }}
        </template>
      </el-table-column>
      <el-table-column label="检测时间段" align="center" width="220">
        <template #default="{ row }">
          {{ row.pollStartTime && row.pollEndTime
            ? `${row.pollStartTime.substring(0, 5)} 至 ${row.pollEndTime.substring(0, 5)}`
            : '未设置' }}
        </template>
      </el-table-column>

      <!-- <el-table-column label="创建用户" align="center" prop="createByName" /> -->
      <!-- <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">

          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:timers:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:timers:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改预警定时对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="timersRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="定时名称" prop="timerName">
          <el-input v-model="form.timerName" placeholder="请输入定时器名称" />
        </el-form-item>
        <el-form-item label="订阅匹配" prop="usersubId">
          <el-select v-model="form.usersubId" placeholder="请选择订阅" clearable filterable>
            <el-option v-for="item in usersubOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="effectiveStartTime">
          <el-date-picker clearable v-model="form.effectiveStartTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预警开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="effectiveEndTime">
          <el-date-picker clearable v-model="form.effectiveEndTime" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择预警结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="轮询类型" prop="pollType">
          <el-select v-model="form.pollType">
            <el-option label="固定时间（如每天18点至23点检测）" value="fixedtime" />
            <el-option label="时间间隔（如每间隔10个小时检测）" value="interval" />
          </el-select>
        </el-form-item>
        <el-form-item label="开始时间" v-if="form.pollType === 'fixedtime'">
          <el-time-picker v-model="form.pollStartTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="请选择开始时间"
            :editable="false" />
        </el-form-item>
        <el-form-item label="结束时间" v-if="form.pollType === 'fixedtime'">
          <el-time-picker v-model="form.pollEndTime" format="HH:mm:ss" value-format="HH:mm:ss" placeholder="请选择结束时间"
            :editable="false" />
        </el-form-item>

        <el-form-item label="轮询小时" v-if="form.pollType === 'interval'">
          <el-input-number v-model="form.pollInterval" :min="1" />
        </el-form-item>
        <!-- <el-form-item label="状态" prop="timerStatus">
          <el-input v-model="form.timerStatus" placeholder="请输入状态" />
        </el-form-item> -->
        <el-form-item label="状态" prop="timerStatus">
          <el-select v-model="form.timerStatus" placeholder="请设置状态" clearable>
            <el-option label="启动" value="active" />
            <el-option label="挂起" value="close" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Timers">
import { listTimers, getTimers, delTimers, addTimers, updateTimers } from "@/api/agriculture/znjc/timers"
import { listUsersub, getUsersub } from "@/api/agriculture/znjc/usersub"
import { getUser, getUserProfile } from "@/api/system/user"
import { processRuleswarnlogByTimerId } from '@/api/agriculture/znjc/ruleswarnlog'
import { watch } from 'vue'





const { proxy } = getCurrentInstance()
const usersubOptions = ref([])
const timerNameOptions = ref([])

const timersList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    timerId: null,
    usersubId: null,
    effectiveStartTime: null,
    effectiveEndTime: null,
    pollInterval: null,
    timerName: null,
    timerStatus: null,
    pollType: null,
    pollStartTime: null,
    pollEndTime: null,
    createBy: null,
    createTime: null,
    updateTime: null
  },
  rules: {
    usersubId: [{ required: true, message: '请选择订阅', trigger: 'change' }],
    effectiveStartTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    effectiveEndTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    pollInterval: [{ required: true, message: '请输入检测间隔', trigger: 'blur' }],
    timerName: [{ required: true, message: '请输入定时器名称', trigger: 'blur' }],
    timerStatus: [{ required: true, message: '请选择状态', trigger: 'change' }],
    pollType: [{ required: true, message: '请选择轮询类型', trigger: 'change' }]

  }
})


const { queryParams, form, rules } = toRefs(data)
/** 查询预警定时列表 */
function getList() {
  loading.value = true
  listTimers(queryParams.value).then(async response => {
    const list = response.rows
    console.log(list)
    // 并发查询创建者姓名和订阅名称
    const promises = list.map(async item => {
      // 获取创建者姓名
      if (item.createBy) {
        try {
          const res = await getUser(item.createBy)
          item.createByName = res.data.userName || item.createBy
        } catch {
          item.createByName = item.createBy // 回退
        }
      } else {
        item.createByName = '无'
      }

      // 获取订阅名称
      if (item.usersubId) {
        try {
          const res = await getUsersub(item.usersubId)
          // 假设返回格式是 res.data.subName（你可以根据接口调整）
          item.usersubName = res.data.subName || item.usersubId
        } catch {
          item.usersubName = item.usersubId // 回退
        }
      } else {
        item.usersubName = '无'
      }

      return item
    })

    timersList.value = await Promise.all(promises)
    total.value = response.total
    loading.value = false
  })
}


// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    timerId: null,
    usersubId: null,
    effectiveStartTime: null,
    effectiveEndTime: null,
    pollInterval: null,
    timerName: null,
    timerStatus: null,
    createBy: null,
    createTime: null,
    updateTime: null,
    pollType: null,
    startTime: null,
    endTime: null
  }
  proxy.resetForm("timersRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.timerId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
async function handleAdd() {
  reset()
  try {
    const res = await getUserProfile();
    form.value.createBy = res.data.userId;  // 设置当前用户ID到创建者字段
  } catch (error) {
    console.error("获取当前用户信息失败:", error);
  }
  open.value = true
  title.value = "添加预警定时"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _timerId = row.timerId || ids.value
  getTimers(_timerId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改预警定时"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["timersRef"].validate(valid => {

    if (valid) {
      // 互斥字段处理
      if (form.value.pollType === '时间间隔') {
        // 只留pollInterval，时间段清空
        form.value.pollStartTime = null
        form.value.pollEndTime = null
      } else if (form.value.pollType === '固定时间') {
        // 只留时间段，检测间隔清空
        form.value.pollInterval = null
      }

      console.log("提交的内容:", JSON.stringify(form.value, null, 2))

      if (form.value.timerId != null) {
        updateTimers(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addTimers(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}


/** 删除按钮操作 */
function handleDelete(row) {
  const _timerIds = row.timerId || ids.value
  proxy.$modal.confirm('是否确认删除预警定时编号为"' + _timerIds + '"的数据项？').then(function () {
    return delTimers(_timerIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => { })
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/timers/export', {
    ...queryParams.value
  }, `timers_${new Date().getTime()}.xlsx`)
}


async function loadUsersubOptions() {
  try {
    const res = await listUsersub({ pageNum: 1, pageSize: 1000 })
    usersubOptions.value = res.rows.map(item => ({
      label: item.subName,
      value: item.subId
    }))
  } catch (error) {
    console.error('加载订阅列表失败', error)
  }
}

async function loadTimerNameOptions() {
  try {
    const res = await listTimers({ pageNum: 1, pageSize: 1000 }) // 或根据实际接口限制调整
    const nameSet = new Set()
    res.rows.forEach(item => {
      if (item.timerName) {
        nameSet.add(item.timerName)
      }
    })
    timerNameOptions.value = [...nameSet]
  } catch (error) {
    console.error("加载定时器名称失败", error)
  }
}

async function handleProcessByTimerId(timerId) {
  if (!timerId) {
    proxy.$message.warning('无效的定时器ID')
    return
  }
  try {
    const res = await processRuleswarnlogByTimerId(timerId)
    proxy.$message.success(res.msg || '处理成功')
    getList()
  } catch (error) {
    proxy.$message.error('处理失败：' + (error.message || '未知错误'))
  }
}

watch(() => form.value.pollType, (newType, oldType) => {
  if (newType === '固定时间' && oldType === '时间间隔') {
    // 从时间间隔切换到固定时间，清空时间段相关字段
    form.value.pollStartTime = null
    form.value.pollEndTime = null
  } else if (newType === '时间间隔' && oldType === '固定时间') {
    // 从固定时间切换到时间间隔，清空间隔字段
    form.value.pollInterval = null
  }
})

onMounted(() => {
  loadUsersubOptions()
  loadTimerNameOptions()
})


getList()
</script>
